package cn.wolfcode.crm.util;

import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.domain.Permission;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import java.util.Iterator;
import java.util.List;

public class MenuUtil {
    public  static  final  String  MENU_IN_SESSION="menu_in_session";
    //递归删除菜单
    private static void filterSystemMenu(List<Menu> menus){
        //过去到当前用户所有的菜单
        Subject subject = SecurityUtils.getSubject();
        //遍历集合,判断menu菜单权限是否在对应的权限集合中
        Iterator<Menu> iter = menus.iterator();
        while (iter.hasNext()){
            Menu menu = iter.next();
            //获取菜单绑定的权限url
            Permission permission = menu.getPermission();
            if(permission!=null){
                //判断当前登录的用户是否有权限
                if (subject.isPermitted(permission.getResource())){
                    //不在,删除
                    iter.remove();
                }
            }
            //如果有儿子,也要进行迭代判断
            List<Menu> children = menu.getChildren();
            while (children!=null&&children.size()>0){
                filterSystemMenu(children);
            }
        }
    }
    //优化,删除不存在子菜单的空菜单
    public static void filterMenu(List<Menu> menus) {
        //过滤菜单
        filterSystemMenu(menus);
        //删除无儿子的父菜单
        Iterator<Menu> iter = menus.iterator();
        while (iter.hasNext()){
            Menu menu = iter.next();
            if(menu.getChildren()==null&&menu.getChildren().size()==0){
                iter.remove();
            }
        }
    }
}
